import re
import time

from django.utils import timezone
import redis
from django.db.models import Q
from django.contrib.sessions.models import Session
from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from django.core.cache import cache
from django.contrib.auth import authenticate,login,logout
from django.core.cache import cache
from oneself import models
from oneself.models import UserMenber
from home import restful
from oneself.models import User
from home.ask import aliyunsms
from home.random_username import UserRange
# Create your views here.


#首页
def homepage(request):
    username = request.COOKIES.get('username')
    print('username****=====****',username)
    if username is not None:
        print("username==",username)
        member_id=User.objects.get(username=username).member_id
        print("member_id=====",member_id)
        member=UserMenber.objects.get(id=member_id).rember
        print("a===",member)
        return render(request, "home/home1.html",{"member":member})
    else:
        return render(request, "home/home1.html")

#注册
# 阿里云短信下发 验证
def test_redis(request):
    #存储数据
    cache.set('name','tom',360000) # 该值的的有效期为20S
    # 判断redis中是否存在
    print(cache.has_kay('name')) # 包含true
    # 获取
    print(cache.get('name'))  # 返回： tom 无返回null
    return HttpResponse('测试redis')

# 发短信接口
def sms_send(request):
    # http://localhost:8000/duanxin/duanxin/sms_send/?phone=18434288349
    # 1 获取手机号
    phone = request.GET.get('phone')
    # 2 生成6位验证码
    code = aliyunsms.get_code(6, False)
    # 3 缓存到Redis
    cache.set(phone,code,360000) #60s有效期
    print('判断缓存中是否有:',cache.has_key(phone))
    print('获取Redis验证码:',cache.get(phone))
    # 4 发短信
    result = aliyunsms.send_sms(phone, code)
    return HttpResponse(result)

# 短信验证码校验
def sms_check(request):
    # /duanxin/sms_check/?phone=xxx&code=xxx
    # 1. 电话和手动输入的验证码
    phone = request.GET.get('phone')
    code = request.GET.get('code')

    # 2. 获取redis中保存的code
    print('缓存中是否包含:',cache.has_key(phone))
    print('取值:',cache.get(phone))
    cache_code = cache.get(phone)
    # 3. 判断
    if code == cache_code:
        # 格式统一调整后的
        # return HttpResponse(json.dumps({'result':'OK'}))
        return restful.ok('Ok', data=None)
    else:
        # 格式统一调整后的
        # return HttpResponse(json.dumps({'result':'False'}))
        return restful.params_error('验证码错误', data=None)

# 338923

def register(request):
    return render(request,'home/register.html')
def register_handle(request,hid):
    print('HID=',hid)
    if hid=="0":
        if request.method.lower()=='post':
            email=request.POST.get('email')
            print("email====",email)
            password=request.POST.get('pwd')
            password2=request.POST.get('cpwd')
            allow=request.POST.get('allow')
            if not all([email,password,password2,allow]):
                return render(request,'home/register.html',{"error_msg":"1数据不完整"})
            if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$', email):
                return render(request, "home/register.html", {"error_msg": "邮箱格式不正确"})
            if allow != "on":
                return render(request, "home/register.html", {"error_msg": "请勾选同意协议"})
            try:
                user = User.objects.get(email=email)
                print("***user=====****",user)
            except User.DoesNotExist:
                user=None
            if user:
                return render(request, 'home/register.html', {"error_msg": "邮箱已经存在"})
            print("email",email)
            print(password2)
            username=UserRange().RangeUsername()
            birth=UserRange().current_time()
            print(username)
            print(birth)
            # print(User)
            User.objects.create_user(username=username,email=email,password=password2,birth=birth)

            return render(request,'home/login.html')

    elif hid=="1":
        if request.method.lower()=='post':
            phone=request.POST.get('phone')
            code=request.POST.get('code')
            password1=request.POST.get('pwdd')
            password22=request.POST.get("cpwd1")
            allow1=request.POST.get('allow1')
            if not all([phone,code,password1,password22,allow1]):
                return render(request, 'home/register.html', {"error_msg1": "数据不完整"})
            if not re.match(r'^1[35678]\d{9}$',phone):
                return render(request,'home/register.html',{'error_msg1': "输入的电话号码有误"})
            if allow1 != "on":
                return render(request,'home/register.html',{"error_msg1": "请勾选同意协议"})
            try:
                user = User.objects.get(phone=phone)
            except User.DoesNotExist:
                """如果出现该异常说明用户名不存在，则让user对象为空"""
                user = None
            if user:
                return render(request, 'home/register.html', {"error_msg1": "手机号码已经存在"})
            print(user)
            username = UserRange().RangeUsername()
            birth = UserRange().current_time()
            User.objects.create_user(phone=phone, password=password22,username=username,birth=birth)

            return render(request,'home/login.html')

#登录

def verify(account):
    print("account=========",account)
    try:
        if re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$', account):
            user=User.objects.get(email=account)
        elif re.match(r'^1[35678]\d{9}$',account):
            user=User.objects.get(phone=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    return user
def login_handle(request):
    if request.method.lower()=='get':
        return render(request,'home/login.html')



    if request.method.lower()=='post':
        username=request.POST.get('uname')
        password=request.POST.get('password')
        remember_me=request.POST.get('rember_me')
        # print("username:======",username)
        # print("password:======",password)
        # print(remember_me)
        if not all([username,password,remember_me]):
            return render(request,'home/login.html',{'error_msg':'数据不完整'})
        username = verify(username)
        # print("useranme=====",username)
        user=User.objects.filter(Q(email=username) | Q(phone=username) | Q(username=username)).values_list("username",flat=True)
        print('aq====',user)
        if user:
            # print("user====*********", user[0])
            user=authenticate(username=user[0],password=password)
            print('user=*****//===',user)
            if user is not None:
                print("*************************", user)
                # 调用login函数，实现对request进行操作，将用户信息、session、cookies等写入了request中，再用render将request进行返回
                login(request,user)
                print('sessionid====',request.session.session_key)
                response=redirect(reverse('home:homepage'))
                if remember_me or not remember_me:
                    response.set_cookie("username",user,max_age=7 * 24 * 3600)
                    # request.session['is_login'] = 'True'
                    return response
                else:
                    response.delete_cookie('username')
                    return response
            else:
                return render(request,'home/login.html',{"error_msg":"您的用户名、邮箱、手机号错误或密码错误，请检查后再次登录"})
        else:
            return render(request,'home/login.html',{"error_msg":"用户名不存在"})


# 退出登录
def my_logout(request):
    response = redirect(reverse('home:homepage'))
    response.delete_cookie('username')
    logout(request)
    return response




#全部分类
def sort(request):
    return render(request, "home/sort.html")

#商品页面
def introduction(request):
    return render(request, "home/introduction.html")

#搜索
def search(request):
    return render(request, "home/search.html")

#购物车
def shopcart(request):
    return render(request, "home/shopcart.html")

#结算
def pay(request):
    return render(request, "home/pay.html")

#结算成功
def success(request):
    return render(request, "home/success.html")